<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';

import { Page } from '@vben/common-ui';
import { useDesign } from '@vben/hooks';
import { IconifyIcon } from '@vben/icons';

import { Button, DatePicker, Table } from 'ant-design-vue';
import dayjs from 'dayjs';

const { prefixCls } = useDesign('profit-annual');

// 响应式数据
const loading = ref(false);
const selectedYear = ref(dayjs('2025', 'YYYY'));

// 表格列配置
const columns = [
  {
    title: '项目',
    dataIndex: 'project',
    key: 'project',
    width: 350,
    fixed: 'left',
  },
  {
    title: '行次',
    dataIndex: 'lineNumber',
    key: 'lineNumber',
    width: 80,
    align: 'center',
  },
  {
    title: '本年累计金额',
    dataIndex: 'currentYear',
    key: 'currentYear',
    width: 150,
    align: 'right',
  },
  {
    title: '上年累计金额',
    dataIndex: 'lastYear',
    key: 'lastYear',
    width: 150,
    align: 'right',
  },
];

// 原始利润表年报数据
const originalAnnualData = [
  {
    key: 'revenue',
    project: '一、营业收入',
    lineNumber: 1,
    currentYear: 2_500_000,
    lastYear: 2_200_000,
    level: 1,
    hasChildren: false,
    expanded: false,
  },
  {
    key: 'cost',
    project: '减：营业成本',
    lineNumber: 2,
    currentYear: 1_500_000,
    lastYear: 1_320_000,
    level: 1,
    hasChildren: false,
    expanded: false,
  },
  {
    key: 'taxes',
    project: '营业税金及附加',
    lineNumber: 3,
    currentYear: 75_000,
    lastYear: 66_000,
    level: 1,
    hasChildren: true,
    expanded: false,
    children: [
      {
        key: 'taxes-consumption',
        project: '消费税',
        lineNumber: 11,
        currentYear: 25_000,
        lastYear: 22_000,
        level: 2,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'taxes-business',
        project: '营业税',
        lineNumber: 12,
        currentYear: 20_000,
        lastYear: 18_000,
        level: 2,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'taxes-city',
        project: '城市维护建设税',
        lineNumber: 13,
        currentYear: 15_000,
        lastYear: 13_200,
        level: 2,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'taxes-education',
        project: '教育费附加',
        lineNumber: 14,
        currentYear: 10_000,
        lastYear: 8800,
        level: 2,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'taxes-other',
        project: '其他',
        lineNumber: 15,
        currentYear: 5000,
        lastYear: 4000,
        level: 2,
        hasChildren: false,
        expanded: false,
      },
    ],
  },
  {
    key: 'selling-expenses',
    project: '销售费用',
    lineNumber: 4,
    currentYear: 125_000,
    lastYear: 110_000,
    level: 1,
    hasChildren: true,
    expanded: false,
    children: [
      {
        key: 'selling-salary',
        project: '销售人员薪酬',
        lineNumber: 16,
        currentYear: 75_000,
        lastYear: 66_000,
        level: 2,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'selling-advertising',
        project: '广告宣传费',
        lineNumber: 17,
        currentYear: 40_000,
        lastYear: 35_200,
        level: 2,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'selling-other',
        project: '其他销售费用',
        lineNumber: 18,
        currentYear: 10_000,
        lastYear: 8800,
        level: 2,
        hasChildren: false,
        expanded: false,
      },
    ],
  },
  {
    key: 'admin-expenses',
    project: '管理费用',
    lineNumber: 5,
    currentYear: 175_000,
    lastYear: 154_000,
    level: 1,
    hasChildren: true,
    expanded: false,
    children: [
      {
        key: 'admin-salary',
        project: '管理人员薪酬',
        lineNumber: 19,
        currentYear: 120_000,
        lastYear: 105_600,
        level: 2,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'admin-office',
        project: '办公费用',
        lineNumber: 20,
        currentYear: 35_000,
        lastYear: 30_800,
        level: 2,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'admin-other',
        project: '其他管理费用',
        lineNumber: 21,
        currentYear: 20_000,
        lastYear: 17_600,
        level: 2,
        hasChildren: false,
        expanded: false,
      },
    ],
  },
  {
    key: 'finance-expenses',
    project: '财务费用',
    lineNumber: 6,
    currentYear: 40_000,
    lastYear: 35_200,
    level: 1,
    hasChildren: false,
    expanded: false,
  },
  {
    key: 'operating-profit',
    project: '二、营业利润（亏损以"-"号填列）',
    lineNumber: 7,
    currentYear: 585_000,
    lastYear: 514_800,
    level: 1,
    hasChildren: false,
    expanded: false,
  },
  {
    key: 'non-operating-income',
    project: '加：营业外收入',
    lineNumber: 8,
    currentYear: 25_000,
    lastYear: 22_000,
    level: 1,
    hasChildren: false,
    expanded: false,
  },
  {
    key: 'non-operating-expenses',
    project: '减：营业外支出',
    lineNumber: 9,
    currentYear: 10_000,
    lastYear: 8800,
    level: 1,
    hasChildren: false,
    expanded: false,
  },
  {
    key: 'total-profit',
    project: '三、利润总额（亏损总额以"-"号填列）',
    lineNumber: 10,
    currentYear: 600_000,
    lastYear: 528_000,
    level: 1,
    hasChildren: false,
    expanded: false,
  },
  {
    key: 'income-tax',
    project: '减：所得税费用',
    lineNumber: 22,
    currentYear: 150_000,
    lastYear: 132_000,
    level: 1,
    hasChildren: false,
    expanded: false,
  },
  {
    key: 'net-profit',
    project: '四、净利润（净亏损以"-"号填列）',
    lineNumber: 23,
    currentYear: 450_000,
    lastYear: 396_000,
    level: 1,
    hasChildren: false,
    expanded: false,
  },
];

// 计算表格数据（包含展开/折叠逻辑）
const tableData = computed(() => {
  const result: any[] = [];

  const processItems = (items: any[]) => {
    items.forEach((item) => {
      result.push(item);
      if (item.hasChildren && item.expanded && item.children) {
        processItems(item.children);
      }
    });
  };

  processItems(originalAnnualData);
  return result;
});

// 切换展开/折叠
const toggleExpand = (key: string) => {
  const findAndToggle = (items: any[]): boolean => {
    for (const item of items) {
      if (item.key === key) {
        item.expanded = !item.expanded;
        return true;
      }
      if (item.children && findAndToggle(item.children)) {
        return true;
      }
    }
    return false;
  };

  findAndToggle(originalAnnualData);
};

// 格式化金额
const formatAmount = (amount: null | number | undefined): string => {
  if (amount === null || amount === undefined) return '';
  return new Intl.NumberFormat('zh-CN').format(amount);
};

// 获取行样式类名
const getRowClassName = (record: any): string => {
  const classes = [];

  if (record.level === 1) {
    classes.push('font-medium');
  }

  if (
    record.project.includes('一、') ||
    record.project.includes('二、') ||
    record.project.includes('三、') ||
    record.project.includes('四、')
  ) {
    classes.push('bg-gray-50');
  }

  return classes.join(' ');
};

// 事件处理函数
const handlePrint = () => {
  window.print();
};

const handleDownload = () => {
  // 这里可以实现下载功能
  // eslint-disable-next-line no-console
  console.log('下载利润表年报');
};

// 初始化数据
const initData = () => {
  loading.value = true;
  // 模拟数据加载
  setTimeout(() => {
    loading.value = false;
  }, 500);
};

onMounted(() => {
  initData();
});
</script>

<template>
  <Page
    auto-content-height
    :class="prefixCls"
    content-class="flex flex-col gap-4 p-4"
    :loading="loading"
    title="利润表年报"
  >
    <!-- 顶部信息栏 -->
    <div class="rounded-lg bg-white p-4 shadow-sm">
      <div class="mb-4 flex items-center justify-between">
        <div class="flex items-center gap-4">
          <span class="text-sm text-gray-600">编制单位：</span>
          <span class="font-medium">北京神州源科技有限公司</span>
        </div>
        <div class="flex items-center gap-4">
          <span class="text-sm text-gray-600">账期：</span>
          <DatePicker
            v-model:value="selectedYear"
            picker="year"
            placeholder="选择年度"
            format="YYYY"
            class="w-32"
          />
        </div>
        <div class="flex gap-2">
          <Button type="primary" @click="handlePrint">
            <template #icon>
              <IconifyIcon icon="lucide:printer" />
            </template>
            打印
          </Button>
          <Button type="primary" @click="handleDownload">
            <template #icon>
              <IconifyIcon icon="lucide:download" />
            </template>
            下载
          </Button>
        </div>
      </div>
    </div>

    <!-- 利润表年报表格 -->
    <div class="overflow-hidden rounded-lg bg-white shadow-sm">
      <Table
        :columns="columns"
        :data-source="tableData"
        :pagination="false"
        :scroll="{ x: 1000, y: 600 }"
        size="small"
        bordered
        :row-class-name="getRowClassName"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'project'">
            <div class="flex items-center">
              <Button
                v-if="record.hasChildren"
                type="text"
                size="small"
                class="mr-2 h-4 w-4 p-0"
                @click="toggleExpand(record.key)"
              >
                <IconifyIcon
                  :icon="record.expanded ? 'lucide:minus' : 'lucide:plus'"
                  class="text-xs"
                />
              </Button>
              <span
                :class="{
                  'font-medium': record.level === 1,
                  'ml-4': record.level === 2,
                  'ml-8': record.level === 3,
                }"
              >
                {{ record.project }}
              </span>
            </div>
          </template>
          <template v-else-if="column.key === 'lineNumber'">
            {{ record.lineNumber }}
          </template>
          <template v-else-if="column.key === 'currentYear'">
            <span class="block text-right">
              {{ formatAmount(record.currentYear) }}
            </span>
          </template>
          <template v-else-if="column.key === 'lastYear'">
            <span class="block text-right">
              {{ formatAmount(record.lastYear) }}
            </span>
          </template>
        </template>
      </Table>
    </div>
  </Page>
</template>

<style scoped>
.profit-annual {
  .ant-table-thead > tr > th {
    background-color: #fafafa;
    font-weight: 600;
    text-align: center;
  }

  .ant-table-tbody > tr > td {
    padding: 8px 12px;
  }

  .ant-table-tbody > tr.bg-gray-50 > td {
    background-color: #f9fafb;
  }

  .ant-table-tbody > tr:hover > td {
    background-color: #f0f9ff !important;
  }
}
</style>
